package com.yxsk.relay.job.endpoint.combine.auto.config.components;

import com.yxsk.relay.job.component.endpoint.config.RelayJobSlaveConfig;
import com.yxsk.relay.job.component.endpoint.log.logger.RelayJobLoggerFactory;
import com.yxsk.relay.job.component.endpoint.log.stream.LocalDiskLogStream;
import com.yxsk.relay.job.component.endpoint.log.stream.LogStream;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description 应用启动时初始化日志
 * @Author 11376
 * @CreateTime 2019/9/17 14:33
 */
@Configuration
public class RelayJobLogServiceApplicationListener implements ApplicationContextInitializer {

    private static LogStream applicationLogStream;

    @Override
    public void initialize(ConfigurableApplicationContext context) {
        LocalDiskLogStream localDiskLogStream = new LocalDiskLogStream(getEnvProperty(context, "relay.job.slave.logRootPath", RelayJobSlaveConfig.DEFAULT_LOG_ROOT_PATH));
        localDiskLogStream.init();

        RelayJobLoggerFactory.init(localDiskLogStream, getEnvProperty(context, "relay.job.slave.logPattern", RelayJobSlaveConfig.DEFAULT_LOG_PATTERN));

        applicationLogStream = localDiskLogStream;
    }

    @Bean
    public LogStream logStream() {
        return applicationLogStream;
    }

    private String getEnvProperty(ConfigurableApplicationContext applicationContext, String key, String defaultValue) {
        String value = applicationContext.getEnvironment().getProperty(key);
        if (StringUtils.isEmpty(value)) {
            value = applicationContext.getEnvironment().getProperty(humpToLine2(key));
        }
        return StringUtils.isEmpty(value) ? defaultValue : value;
    }

    private static Pattern humpPattern = Pattern.compile("[A-Z]");

    public static String humpToLine2(String str) {
        Matcher matcher = humpPattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "-" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

}
